<template>
  <view class="choose-address-container">
    <!-- 地址列表 -->
    <scroll-view 
      scroll-y 
      class="address-list"
      @scrolltolower="loadMore"
      :scroll-top="scrollTop"
    >
      <view v-for="(item, index) in addressList" :key="index" class="address-item" @click="selectAddress(item)">
        <view class="address-icon">
          <uv-icon name="map-fill" :color="'#FF6B35'" :size="20" />
        </view>
        <view class="address-content">
          <view class="address-header">
            <text class="address-name">{{ item.province }}{{ item.city }}{{ item.region }}</text>
            <uv-tags 
              v-if="item.is_default == 'Y'" 
              text="默认" 
              plain 
              size="mini" 
              type="warning"
              customStyle="margin-left: 12rpx;"
            />
          </view>
          <text class="address-detail">{{ item.address_detail }}</text>
          <text class="contact-info">{{ item.address_name }} {{ item.address_mobile }}</text>
        </view>
        <view class="address-actions">
          <view class="action-btn" @click.stop="editAddress(item)">
            <uv-icon name="edit-pen" :color="'#999'" :size="18" />
          </view>
          <view class="action-btn" style="margin-left: 12rpx;" @click.stop="deleteAddress(item)">
            <uv-icon name="trash" :color="'#f56c6c'" :size="18" />
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!loading && !hasMore && addressList.length > 0" class="no-more-container">
        <text class="no-more-text">没有更多数据了</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && addressList.length === 0" class="empty-container">
        <uv-icon name="map" :color="'#ddd'" :size="80" />
        <text class="empty-text">暂无保存的地址</text>
      </view>
    </scroll-view>


    <view style="position: fixed; bottom: 100rpx; right: 20rpx; z-index: 9;">
      <uv-icon name="plus-circle-fill" :color="'#FF6B35'" :size="40" @click="addAddress"/>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRequest } from '@/api'
const { GET_ADRESS_LIST ,DEL_ADRESS} = useRequest()
import { UserInfoManager } from '@/utils/userInfo'

const addressList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const scrollTop = ref(0)

// 分页参数
const current = ref(1)
const pageSize = ref(10)

// 选择地址
const selectAddress = (item: any) => {
  // 返回上一页并传递选中的地址
  uni.$emit('refList',item)

  uni.navigateBack()
}

// 编辑地址
const editAddress = (item: any) => {
  uni.navigateTo({
    url: `/user/home/editAddress?id=${item.id}`
  })
}

// 添加地址
const addAddress = () => {
  uni.navigateTo({
    url: `/user/home/editAddress`
  })
}
// 获取地址列表
const getList = async (isLoadMore = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const params = {
      isdriver: UserInfoManager.lastrole(),
      page: current.value,
      page_size: pageSize.value
    }
    
    const res = await GET_ADRESS_LIST(params)
    if (res.code === 1) {
      const newData = res.data.data || []
      
      if (isLoadMore) {
        // 上拉加载更多，追加数据
        addressList.value = [...addressList.value, ...newData]
      } else {
        // 首次加载，替换数据
        addressList.value = newData
      }
      
      // 判断是否还有更多数据
      hasMore.value = addressList.value.length < (res.data.total || 0)
    } else {
      uni.showToast({ title: res.msg || '获取地址列表失败', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: '获取地址列表失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 重置分页
const resetPagination = () => {
  current.value = 1
  hasMore.value = true
  addressList.value = []
}

// 加载更多
const loadMore = async () => {
  if (loading.value || !hasMore.value) return
  
  current.value++
  await getList(true)
}

onMounted(() => {
  getList()
  
  // 监听地址列表刷新事件
  uni.$on('refreshAddressList', () => {
    setTimeout(() => {
      resetPagination()
      getList()
    }, 200)
  })
})

onUnmounted(() => {
  // 清理事件监听
  uni.$off('refreshAddressList')
})

// 删除地址
const deleteAddress = (item: any) => {
  uni.showModal({
    title: '确认删除',
    content: '删除后不可恢复，是否继续？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        uni.showLoading({ title: '删除中...' })
        const params = {
          id: item.id,
          isdriver: UserInfoManager.lastrole()
        }
        const resp = await DEL_ADRESS(params)
        if (resp.code === 1) {
          uni.showToast({ title: '删除成功', icon: 'success' })
          // 刷新列表
          resetPagination()
          getList()
        }
      } catch (e) {
       
      } finally {
        uni.hideLoading()
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.choose-address-container {
  min-height: 100vh;
  background: #f6f7f9;
}

.address-list {
  height: 100vh;
  padding: 20rpx;
}

.address-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:active {
    background-color: #f8f9fa;
    transform: scale(0.98);
  }
}

.address-icon {
  width: 48rpx;
  height: 48rpx;
  background: #fff5f0;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.address-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 16rpx;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.address-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 44rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 40rpx;
  margin-bottom: 8rpx;
}

.contact-info {
  font-size: 26rpx;
  color: #999;
  line-height: 36rpx;
}

.address-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.action-btn {
  width: 56rpx;
  height: 56rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    background: #f0f0f0;
    transform: scale(0.95);
  }
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 没有更多数据 */
.no-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #999;
}

/* 空状态 */
.empty-container {
  padding: 120rpx 24rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 16rpx;
}
</style>
